﻿package classes
{
	import flash.net.Socket;
	import flash.utils.ByteArray;
	import flash.events.*;
	/**
	 * ...
	 * @author wwx
	 */
	public class TCPSocket
	{
		private var m_socket:Socket = null;
		private var m_strIP:String;
		private var m_iPort:int;
		
		private var m_recvCallbackFun:Function = null;
		
		public function TCPSocket(ip:String, port:int, recvCallbackFun:Function)
		{
			m_strIP = ip;
			m_iPort = port;
			m_recvCallbackFun = recvCallbackFun;
		}
		
		public function setConnectAddr(ip:String, port:int):void
		{
			m_strIP = ip;
			m_iPort = port;
		}
		
		public function connect():int
		{
			if(0 >= m_iPort)
				return -1;
			if (null == m_strIP || 0 >= m_strIP.length)
				return -2;
			this.close();
			m_socket = new Socket();
			m_socket.addEventListener("connect", onConnectHandler);
			m_socket.addEventListener("close", onCloseHandler);
			m_socket.addEventListener("socketData", onDataReceivedHandler);
			m_socket.addEventListener("ioError", onIOErrorHandler);
			m_socket.addEventListener("progress", onProgressHandler);
			m_socket.addEventListener("securityError", onSecurityErrorHandler);
			
			trace("start call connect ...\n");
			this.m_socket.connect(m_strIP, m_iPort);
			trace("end call connect ...\n");
			
			return 0;
		}

		// connect事件的响应函数
		private function onConnectHandler(event:Event):void 
		{
			trace("建立连接 " + event + "\n");	
			m_recvCallbackFun(1,this);
		}

		// close事件的响应函数
		private function onCloseHandler(event:Event):void
		{
			trace("连接关闭 " + event + "\n");
			m_recvCallbackFun(2,this);
		}

		// socketData事件的响应函数，获得数据并显示
		private function onDataReceivedHandler(event:Event):void 
		{
			trace("开始接收数据 " + event + "\n");
			/*
			var strresult:String = "";
			while(mysocket.bytesAvailable > 0 ) {
				var mybyte:uint = mysocket.readUnsignedByte();
				strresult += String.fromCharCode(mybyte);
			}
			trace("接收到数据 " + strresult.substring(1,strresult.length-1) + "\n");
			*/
			
			m_recvCallbackFun(0,this);
		}
		
		public function getBytesAvailable():int
		{
			if (null == m_socket)
				return -1;
			return m_socket.bytesAvailable;
		}

		// ioError事件的响应函数
		private function onIOErrorHandler(event:IOErrorEvent):void 
		{
			trace("IO错误 " + event + "\n");
			m_recvCallbackFun(4,this);
		}

		// progress事件的响应函数
		private function onProgressHandler(event:ProgressEvent):void
		{
			trace("数据加载 " + event.bytesLoaded + " 总数据 " + event.bytesTotal + "\n");
			//m_recvCallbackFun(4);
		}

		// securityError事件的响应函数
		private function onSecurityErrorHandler(event:SecurityErrorEvent):void 
		{
			trace("安全错误 " + event + "\n");
			m_recvCallbackFun(4,this);
		}		
		
		public function close():void
		{
			if (null != this.m_socket)
			{
				this.m_socket.close();
			}
			this.m_socket = null;
		}
		
		public function send(bytes:ByteArray,offset:int,len:int):int
		{
			if (null == m_socket)
				return -1;
			if (0 > offset)
				return -2;
			if (0 >= len)
				return -3;
			if (0 >= bytes.length)
				return -4;
			if (offset + len > bytes.length)
				return -5;
			if (false == m_socket.connected)
				return -6;
			//trace("writeBytes,bytes.length="+bytes.length +",pos="+bytes.position+",offset=" + offset + " " + len);
			m_socket.writeBytes(bytes, offset, len);	
			m_socket.flush();
			//trace("send end____");
			return len;
		}
	
		public function recv(bytes:ByteArray, offset:int, len:int):int
		{
			if (0 > offset)
				return -1;
			if (0 >= len)
				return -2;
			//if (offset + len > bytes.length)
			//	return -3;
			if (null == this.m_socket)
				return -4;
			if (false == m_socket.connected)
				return -5; 
			var ret:int = 0;
			var recvTemp:int = 0;
			while (true == m_socket.connected && ret < len)
			{
				recvTemp = m_socket.bytesAvailable;
				recvTemp = recvTemp >= len? len : recvTemp;
				m_socket.readBytes(bytes, offset + ret, recvTemp);
				ret += recvTemp;
			}
			return ret;
		}
	}
	
}